<template>
  <el-form-item label="富文本">
    <div class="text-editor">
      <el-button link type="primary" @click="handleEdit">在富文本编辑器中修改</el-button>
      <el-dialog v-model="dialogShow" title="富文本编辑" width="1000px">
        <TinymceEditor v-model:modelValue="originValue" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogShow = false">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-form-item>
</template>

<script setup>
import { inject, ref, onMounted } from 'vue'

const { editorForm, domList, backUpdate } = inject('commonForm')
// 初始化属性和元素对应关系
const bindDom = ref(new Set())
const initDomMapping = () => {
  const bindKeys = [`${editorForm.value._key}.richText.value`]
  domList.value.forEach(element => {
    const bindValue = element.getAttribute('_bind')
    bindKeys.forEach(key => {
      if (bindValue.includes(key)) {
        bindDom.value.add(element)
      }
    })
  })
}

const originValue = ref('')
const dialogShow = ref(false)
const handleEdit = () => {
  originValue.value = JSON.parse(JSON.stringify(editorForm.value.richText.value))
  dialogShow.value = true
}
const handleConfirm = () => {
  editorForm.value.richText.value = originValue.value
  bindDom.value.forEach(element => {
    element.innerHTML = editorForm.value.richText.value
  })
  dialogShow.value = false
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

onMounted(() => {
  initDomMapping()
})
</script>

<style lang='scss' scoped>
.text-editor {
  display: flex;
  align-items: center;
  width: 100%;
}
</style>